/*
禁止修改!此文件是产品代码的一部分，后续可能变更或者不再开放。
若有问题，请参考前端相关二开文档。
*/
/*
 * @Author: Fu Zhuohang
 * @Date: 2022-02-17 13:31:00
 * @LastEditors: Fu Zhuohang
 * @LastEditTime: 2022-02-17 17:06:57
 * @FilePath: \yunshu6.0-3\entries\portal\src\views\applications\report-service.ts
 * @Description:
 */
import env from '@/config/env';
// 初始化表单组件配置
import '@/config/h3-form';
import { schema } from 'cloudpivot-form/form';
import { DataItemType } from 'cloudpivot-form/form/src/schema';
import { FieldColumn } from '@h3/report';
import ReportOptions from '@h3/report/dist/options';
import { Component } from 'vue';
import ReportAddress from './report-address.vue';
import ReportCustomSelector from './report-custom-selector.vue';
import ReportDropdown from './report-dropdown.vue';
import ReportSelectSimple from './report-select-simple.vue';
import ReportSelect from './report-select.vue';

import { organizationApi } from 'cloudpivot/api';

let inited = false;

export function init() {
  if (inited) {
    return;
  }

  inited = true;

  ReportOptions.baseUrl = env.portalHost;
  ReportOptions.charts.list.dimension = 50;
  ReportOptions.charts.dimension.supportedTypes = [
    'string',
    'date',
    'address',
    'number',
  ];

  ReportOptions.download.list = true;
  ReportOptions.download.pivotTable = true;

  ReportOptions.requestHeader = () => {
    const token = localStorage.getItem('token');
    if (!token) {
      return null;
    }

    return {
      Authorization: 'Bearer ' + token,
    };
  };
  ReportOptions.filterFormatComponents = (field: any, formula, format) => {
    let components: any = null;
    if (
      field.dataType === DataItemType.Checkbox ||
      field.dataType === DataItemType.Radio ||
      field.dataType === DataItemType.DropdownMulti
    ) {
      components = ReportSelect; // 自定义的筛选组件
    }
    return components;
  };
  ReportOptions.integrateComponents = (
    field: FieldColumn,
    formula: string,
    format: string,
  ): Component | null => {
    let components: any = null;
    switch (field.dataType) {
      case DataItemType.StaffSingle:
      case DataItemType.StaffMulti:
      case DataItemType.StaffDeptMix:
      case DataItemType.DeptMulti:
      case DataItemType.DeptSingle:
        components = ReportCustomSelector;
        break;
      case schema.DataItemType.Address:
        components = ReportAddress;
        break;
      case DataItemType.Dropdown:
      case DataItemType.Checkbox:
      case DataItemType.Radio:
      case DataItemType.DropdownMulti:
        if (format === '2') {
          components = ReportDropdown;
        }
        break;
      default:
        break;
    }
    switch (field.field) {
      case 'sequenceStatus':
        components = ReportSelectSimple;
        break;
      default:
        break;
    }
    return components;
  };

  /**
   * 仪表盘跳转功能
   * https://authine.yuque.com/staff-caknf9/hoagdz/agdooy
   */
  ReportOptions.jumpDashboard = {
    open: true,
    allDashboardList: [],
    allDataTableList: [],
    getJumpUrl: null,
    openMethod: null,
  };

  /**
   * ai统计分析是啊下预览值转为实际值
   */
  ReportOptions.filedNameQueryValue = (field, text) => {
    // 状态与名称映射
    let bizObjectStatusMap = {
      草稿: { value: 'DRAFT', label: '草稿' },
      进行中: { value: 'PROCESSING', label: '进行中' },
      已取消: { value: 'CANCELLED', label: '已取消' },
      已完成: { value: 'COMPLETED', label: '已完成' },
      已作废: { value: 'CANCELED', label: '已作废' },
    };
    // 本人本部门映射
    let selfUserOrDeptMap = {
      本人: { value: 'SELF_P', label: '本人' },
      本部门: { value: 'SELF_D', label: '本部门' },
    };
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
      if (!text || text.length === 0 || !field) {
        resolve(null);
      }
      let resText: any = [];
      switch (field.dataType) {
        case DataItemType.StaffSingle:
        case DataItemType.StaffMulti:
          for (const item of text) {
            if (selfUserOrDeptMap[item] !== undefined) {
              resText.push(selfUserOrDeptMap[item]);
            } else {
              let value = await searchValue(item, 'user');
              if (value.data && value.data.usersTotal) {
                resText.push({
                  label: value.data.users[0].name,
                  value: value.data.users[0].id,
                  type: 3,
                });
              } else {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject({ errorMessage: '查找不到此人员', errorData: text });
                break;
              }
            }
          }
          resolve(resText);
          break;
        case DataItemType.StaffDeptMix:
          for (const item of text) {
            if (selfUserOrDeptMap[item] !== undefined) {
              resText.push(selfUserOrDeptMap[item]);
            } else {
              let value = await searchValue(item, '');
              if (value.data && value.data.usersTotal) {
                resText.push({
                  label: value.data.users[0].name,
                  value: value.data.users[0].id,
                  type: 3,
                });
              } else if (value.data && value.data.departmentsTotal) {
                resText.push({
                  label: value.data.departments[0].name,
                  value: value.data.departments[0].id,
                  type: 1,
                });
              } else {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject({
                  errorMessage: '查找不到此人员或部门',
                  errorData: text,
                });
                break;
              }
            }
          }
          resolve(resText);
          break;
        case DataItemType.DeptMulti:
        case DataItemType.DeptSingle:
          for (const item of text) {
            if (selfUserOrDeptMap[item] !== undefined) {
              resText.push(selfUserOrDeptMap[item]);
            } else {
              let value = await searchValue(item, 'department');
              if (value.data && value.data.departmentsTotal) {
                resText.push({
                  label: value.data.departments[0].name,
                  value: value.data.departments[0].id,
                  type: 3,
                });
              } else {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject({ errorMessage: '查找不到此部门', errorData: text });
                break;
              }
            }
          }
          resolve(resText);
          break;
        default:
          if (field.field === 'sequenceStatus') {
            for (const item of text) {
              if (bizObjectStatusMap[item] !== undefined) {
                resText.push(bizObjectStatusMap[item]);
              } else {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject({
                  errorMessage:
                    '转换流程状态字段失败,目前只支持[进行中,已结束,草稿,已取消]',
                  errorData: item,
                });
                break;
              }
            }
            resolve(resText);
          } else {
            resolve(null);
          }
          break;
      }
    });
  };

  ReportOptions.webConfig = {
    linkProtocol: ['https', 'http'],
  };
}

const searchValue = async (item: any, type: string) => {
  return await organizationApi.search(
    item,
    type,
    '',
    '',
    'root_display',
    'portal',
    '',
    '',
    '',
    '',
    '',
  );
};

init();
